//
//  YZMComposeViewController.swift
//  YZMweibo
//
//  Created by Simon on 16/4/23.
//  Copyright © 2016年 Simon. All rights reserved.
//

import UIKit

class YZMComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
    }
    
    
    //MARK: -  监听方法
    //取消
    @objc private func cancel(){
    dismissViewControllerAnimated(true, completion: nil)
        
    }
    //提交
    @objc private func send(){
        print("发送点击按钮")
    }

    
    //MARK: -  设置UI
    private func setUI(){
        setNav()
        view.backgroundColor = UIColor.whiteColor()
        //添加
        view.addSubview(composeTextView)
        view.addSubview(composeTools)
        composeTextView.addSubview(composePictureView)
        
        composeTextView.snp_makeConstraints { (make) -> Void in
         
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
            
        }
        composeTools.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: ScreenW - 20, height: ScreenW - 20))
            make.leading.equalTo(10)
            make.top.equalTo(composeTextView).offset(100)

        }
        
        // 监听toolbar 按钮点击
        composeTools.composeToolBarColsure = {[weak self](type: YZMComposeToolBarType) in
            switch type{
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.switchKeyborad()
            case .Add:
                print("+")
            }
        }
        // 监听弹出图片控制器
        composePictureView.ComposePictureViewClosure = { [weak self] in
            self?.selectImage()
        }
        
        // 监听键盘弹出frame改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
     
    }
    
    // 监听键盘弹出frame改变方法
    func keyboardWillChangeFrame(noti: NSNotification){
        // 获取键盘的rect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新composeToolBar约束
        composeTools.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - ScreenH)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }

    //MARK: -  设置导航栏
    private func setNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提交", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleViewLazy
    }
    //MARK: -  懒加载控件
    //设置title
    private lazy var titleViewLazy: UILabel = {
        //用户昵称
        let name = YZMUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        //发微博
        let titleString = "发微博\n\(name)"
        //富文本
         let attr = NSMutableAttributedString(string: titleString)
        
        //获得range
        let range = (titleString as NSString).rangeOfString(name)
        
        //设置指定位置的颜色 和字体大小
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        attr.addAttribute(NSForegroundColorAttributeName, value: themColor, range: range)
        let lab = UILabel(textColor: UIColor.darkGrayColor(), textFont: 15)
        lab.attributedText = attr
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.sizeToFit()
     
       return lab
    }()
    //文本输入框
    private lazy var composeTextView: YZMComposeTextVew = {
    
        let view = YZMComposeTextVew()
        view.font = UIFont.systemFontOfSize(16)
        view.delegate = self
        view.placeholder = " hahhaahhahaahhahhaahhahahahahaahahaahhahhaahhahaahhahhaahhahaahhahhaahhahaah"
        view.alwaysBounceVertical = true
        
        return view
    }()
    //底部toolbar
    private lazy var composeTools: YZMComposeToolBar = YZMComposeToolBar()
   
    // 配图
    private lazy var composePictureView: YZMComposePictureView = YZMComposePictureView()
    
    // 自定义表情键盘
    private lazy var emoticonKeyboard: YZMEmoticonKeyboardView = {
        let view = YZMEmoticonKeyboardView()
        view.frame = CGRect(x: 0, y: 0, width: ScreenW, height: 216)
        return view
    }()
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}
//代理
extension YZMComposeViewController: UITextViewDelegate{

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
    
    
}
// MARK: - 处理toolbar 里面的按钮点击事件
extension YZMComposeViewController{

    // 选择image
    func selectImage() {
        let pickerVc =  UIImagePickerController()
        pickerVc.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
            
        }else{
            //print("不能打开照相机")
            presentViewController(pickerVc, animated: true, completion: nil)
        }
    }
    
    // 切换键盘
    func switchKeyborad(){
        // composeTextView.inputView = emoticonKeyboard
        
        /*
         - composeTextView.inputView == nil  代表当前是系统键盘  给他改成自定义表情键盘
         - composeTextView.inputView != nil  代表当前是自定义表情键盘  给他改成系统键盘
         */
        // 表情键盘
        if composeTextView.inputView == nil{
            composeTextView.inputView = emoticonKeyboard
            composeTools.isEmoticon = true
        }else{
            // 系统键盘
            composeTextView.inputView = nil
            composeTools.isEmoticon = false
        }
        // 刷新InputViews
        composeTextView.reloadInputViews()
        // 当我们点击该按钮的时候叫键盘弹出 需要成为第一响应者
        composeTextView.becomeFirstResponder()
    }

}
extension YZMComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    // 用户选择图片后回调方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //        let data = UIImagePNGRepresentation(getImageScale(image, width: 600))
        //
        //       // /Users/apple/Desktop/student.sqlite
        //        data?.writeToFile("/Users/apple/Desktop/1.png", atomically: true)
        //        print(image)
        composePictureView.addImage(getImageScale(image, width: 600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    // 压缩图片
    func getImageScale(image: UIImage, width: CGFloat) -> UIImage{
        // 如果我们的图片宽度小于我们制定的宽度我们直接返回 不处理
        if image.size.width < width{
            return image
        }
        
        /*
         1200  400
         600   x
         */
        let height = (image.size.height * width) / image.size.width
        
        
        // 01 开启上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        // 02 把image渲染到上下文中
        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
        // 03 得到结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        // 04 关闭上下文
        UIGraphicsEndImageContext()
        return result
    }


}
